package com.wzdigit.wms.wms.service.core;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wzdigit.framework.Shift;
import com.wzdigit.framework.utils.DateUtils;
import com.wzdigit.mes.wip.workorder.api.WorkOrderApi;
import com.wzdigit.mes.wip.workorder.api.WorkOrderWipApi;
import com.wzdigit.wms.common.entity.ExcelExportConfig;
import com.wzdigit.wms.common.utils.HttpExcel;
import com.wzdigit.wms.basic.client.Pager;
import com.wzdigit.wms.basic.client.PagerInfo;
import com.wzdigit.wms.basic.client.Queryer;
import com.wzdigit.wms.basic.client.request.report.SettlementReportSearchRequest;
import com.wzdigit.wms.basic.client.response.report.SettlementReportExt;
import com.wzdigit.wms.basic.mapper.core.inventory.GoodsMapper;
import com.wzdigit.wms.basic.mapper.core.inventory.manager.GoodsManagerMapper;
import net.dreamlu.mica.core.utils.DateUtil;
import net.dreamlu.mica.core.utils.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName SettlementReportService
 * @Description 交收报表服务类
 * @Author LHR-PC
 * @Date 2021/1/28 10:27
 * @Version
 **/
@Service
public class SettlementReportService {

    @Autowired
    private GoodsMapper goodsMapper;

    WorkOrderWipApi workOrderWipApi;

    WorkOrderApi workOrderApi;

    @Autowired
    GoodsManagerMapper goodsManagerMapper;

    /**
     * 交收报表
     * @param queryer
     * @return
     */
    public PagerInfo<List<SettlementReportExt>> settlementList(Queryer<SettlementReportSearchRequest> queryer) {
        if (queryer == null) {
            return null;
        }
        Pager<?> page = queryer.getPage();
        if (page == null) {
            page = new Pager<>();
            page.setSkipCount(0);
            page.setMaxResultCount(Integer.MAX_VALUE);
        }

        SettlementReportSearchRequest search = queryer.getRequest();
        if (search.getStatus()!=null && search.getStatus().equals("部分交接")){
            search.setStatus("1");
        }else if (search.getStatus()!=null && search.getStatus().equals("完全交接")){
            search.setStatus("2");
        }else if (search.getStatus()!=null && search.getStatus().equals("生产中")){
            search.setStatus("3");
        }
        if (search.getReceiveTimeBeginLong()!=null){
            search.setReceiveTimeBegin(new Date(search.getReceiveTimeBeginLong()));
        }
        if (search.getReceiveTimeEndLong()!=null){
            search.setReceiveTimeEnd(DateUtils.addSeconds(new Date(search.getReceiveTimeEndLong()),86399));
        }
        try {

            Page<SettlementReportExt> _page= PageHelper.offsetPage(page.getSkipCount(), page.getMaxResultCount());
            PageInfo<SettlementReportExt> result=new PageInfo<>(_page);
            //老版本
            //List<SettlementReportExt> list = goodsManagerMapper.searchSettlementReport(search);
            //新版本
            //List<SettlementReportExt> list = goodsManagerMapper.searchNewSettlementReport(search);
            //2022-01-04
            List<SettlementReportExt> list = goodsManagerMapper.searchNewSettlementReportNoView(search);

            setStatus(list);
            result.setList(list);
            PagerInfo pagerInfo = new PagerInfo();
            pagerInfo.setTotalCount(_page.getTotal());
            pagerInfo.setItems(list);
            return pagerInfo;
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public PagerInfo<List<SettlementReportExt>> settlementListDay(Queryer<SettlementReportSearchRequest> queryer) {
        if (queryer == null) {
            return null;
        }
        Pager<?> page = queryer.getPage();
        if (page == null) {
            page = new Pager<>();
            page.setSkipCount(0);
            page.setMaxResultCount(Integer.MAX_VALUE);
        }

        SettlementReportSearchRequest search = queryer.getRequest();
        if (search.getStatus()!=null && search.getStatus().equals("部分交接")){
            search.setStatus("1");
        }else if (search.getStatus()!=null && search.getStatus().equals("完全交接")){
            search.setStatus("2");
        }else if (search.getStatus()!=null && search.getStatus().equals("生产中")){
            search.setStatus("3");
        }
        if (search.getReceiveTimeBeginLong()!=null){
            search.setReceiveTimeBegin(new Date(search.getReceiveTimeBeginLong()));
        }
        if (search.getReceiveTimeEndLong()!=null){
            search.setReceiveTimeEnd(DateUtils.addSeconds(new Date(search.getReceiveTimeEndLong()),86399));
        }
        try {
   /*         long startTime = System.currentTimeMillis();
*/
            Page<SettlementReportExt> _page= PageHelper.offsetPage(page.getSkipCount(), page.getMaxResultCount());
            PageInfo<SettlementReportExt> result=new PageInfo<>(_page);
            //老版本
          //  List<SettlementReportExt> list = goodsManagerMapper.searchSettlementReportTset(search);
            List<SettlementReportExt> list = goodsManagerMapper.searchNewSettlementDayReport(search);
            //新版本
            //List<SettlementReportExt> list = goodsManagerMapper.searchNewSettlementReport(search);
            setStatus(list);
            result.setList(list);
            PagerInfo pagerInfo = new PagerInfo();
            pagerInfo.setTotalCount(_page.getTotal());
            pagerInfo.setItems(list);

            /*long endTime = System.currentTimeMillis();

            System.out.println("新版本执行时间:"+(endTime-startTime));*/

            return pagerInfo;
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void setStatus(List<SettlementReportExt> list)  {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (SettlementReportExt settlementReportExt : list) {
            if (settlementReportExt.getRealReceivedQty()!=null && settlementReportExt.getRealReceivedQty().compareTo(BigDecimal.ZERO)!=0){
                settlementReportExt.setStatus("部分交接");
            }
            if (settlementReportExt.getOrderQty()!=null && settlementReportExt.getOrderQty().compareTo(BigDecimal.ZERO)!=0
            && settlementReportExt.getRealReceivedQty()!=null && settlementReportExt.getRealReceivedQty().compareTo(BigDecimal.ZERO)!=0
            && settlementReportExt.getMesUnderlineQty()!=null && settlementReportExt.getMesUnderlineQty().compareTo(BigDecimal.ZERO)!=0){
                if (settlementReportExt.getOrderQty().compareTo(settlementReportExt.getMesUnderlineQty())==0
                && settlementReportExt.getOrderQty().compareTo(settlementReportExt.getRealReceivedQty())==0){
                    settlementReportExt.setStatus("完全交接");
                }
            }
            if (settlementReportExt.getRealReceivedQty()!=null &&
                    settlementReportExt.getRealReceivedQty().compareTo(BigDecimal.ZERO)==0){
                settlementReportExt.setStatus("生产中");
            }
            settlementReportExt.setDifferenceQty(settlementReportExt.getMesUnderlineQty().subtract(settlementReportExt.getRealReceivedQty()));
            try {
                if(StringUtil.isNotBlank(settlementReportExt.getCompleteDateString())){
                    settlementReportExt.setCompleteDate(sdf.parse(settlementReportExt.getCompleteDateString()));
                }
                if(StringUtil.isNotBlank(settlementReportExt.getReceivedDateString())){
                    settlementReportExt.setReceivedDate(sdf.parse(settlementReportExt.getReceivedDateString()));
                }
            } catch (ParseException e) {
                e.printStackTrace();
                Shift.fatal("设置日期失败");
            }
        }
    }

    public void exportSettlement(SettlementReportSearchRequest search, HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
        if (search.getStatus()!=null && search.getStatus().equals("部分交接")){
            search.setStatus("1");
        }else if (search.getStatus()!=null && search.getStatus().equals("完全交接")){
            search.setStatus("2");
        }else if (search.getStatus()!=null && search.getStatus().equals("生产中")){
            search.setStatus("3");
        }
        if (search.getReceiveTimeBeginLong()!=null){
            search.setReceiveTimeBegin(new Date(search.getReceiveTimeBeginLong()));
        }
        if (search.getReceiveTimeEndLong()!=null){
            search.setReceiveTimeEnd(DateUtils.addSeconds(new Date(search.getReceiveTimeEndLong()),86399));
        }
        //老版本
        //List<SettlementReportExt> datas = goodsManagerMapper.searchSettlementReport(search);
        //新版本
        List<SettlementReportExt> datas = goodsManagerMapper.searchNewSettlementReportNoView(search);
        setStatus(datas);
        List<ExcelExportConfig> configs = new ArrayList<>();
        configs.add(new ExcelExportConfig("生产工单", "orderNo", 240));
        configs.add(new ExcelExportConfig("订单号", "poNo", 240));
        configs.add(new ExcelExportConfig("物料编码", "materialCode", 240));
        configs.add(new ExcelExportConfig("物料描述", "materialDesc", 240));
        configs.add(new ExcelExportConfig("线体", "lineCode", 240));
        configs.add(new ExcelExportConfig("状态", "status", 240));
        configs.add(new ExcelExportConfig("工单总数", "orderQty", 240));
        configs.add(new ExcelExportConfig("MES下线数", "mesUnderlineQty", 240));
        configs.add(new ExcelExportConfig("实收数", "realReceivedQty", 240));
        configs.add(new ExcelExportConfig("差异数", "differenceQty", 240));
        configs.add(new ExcelExportConfig("接收日期", "receivedDate", 240));
        configs.add(new ExcelExportConfig("销售订单", "so", 240));

        XSSFWorkbook wb = null;
        try {
            wb = HttpExcel.newListToExcel(datas,configs);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        OutputStream outputStream = null;

        try {
            outputStream = servletResponse.getOutputStream();

            String userAgent = servletRequest.getHeader("USER-AGENT");
            String fileName = "交收报表";

            try {
                if (userAgent.contains("Mozilla")) {
                    fileName = new String(fileName.getBytes(), "ISO8859-1");
                } else {
                    fileName = URLEncoder.encode(fileName, "utf8");
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            servletResponse.setCharacterEncoding("UTF-8");
            servletResponse.setContentType("application/octet-stream; charset=UTF-8");// 设置contentType为excel格式
            servletResponse.setHeader("Content-Disposition", "Attachment;Filename=" + fileName + ".xlsx");
            wb.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void exportSettlementDay(SettlementReportSearchRequest search, HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
        if (search.getStatus()!=null && search.getStatus().equals("部分交接")){
            search.setStatus("1");
        }else if (search.getStatus()!=null && search.getStatus().equals("完全交接")){
            search.setStatus("2");
        }else if (search.getStatus()!=null && search.getStatus().equals("生产中")){
            search.setStatus("3");
        }
        if (search.getReceiveTimeBeginLong()!=null){
            search.setReceiveTimeBegin(new Date(search.getReceiveTimeBeginLong()));
        }
        if (search.getReceiveTimeEndLong()!=null){
            search.setReceiveTimeEnd(DateUtils.addSeconds(new Date(search.getReceiveTimeEndLong()),86399));
        }
        //老版本
        List<SettlementReportExt> datas = goodsManagerMapper.searchNewSettlementDayReport(search);
        //新版本
        //List<SettlementReportExt> datas = goodsManagerMapper.searchNewSettlementReport(search);
        setStatus(datas);
        List<ExcelExportConfig> configs = new ArrayList<>();
        configs.add(new ExcelExportConfig("生产工单", "orderNo", 240));
        configs.add(new ExcelExportConfig("订单号", "poNo", 240));
        configs.add(new ExcelExportConfig("物料编码", "materialCode", 240));
        configs.add(new ExcelExportConfig("物料描述", "materialDesc", 240));
        configs.add(new ExcelExportConfig("线体", "lineCode", 240));
        configs.add(new ExcelExportConfig("状态", "status", 240));
        configs.add(new ExcelExportConfig("工单总数", "orderQty", 240));
        configs.add(new ExcelExportConfig("MES下线数", "mesUnderlineQty", 240));
        configs.add(new ExcelExportConfig("实收数", "realReceivedQty", 240));
        configs.add(new ExcelExportConfig("差异数", "differenceQty", 240));
        configs.add(new ExcelExportConfig("接收日期", "receivedDate", 240));
        configs.add(new ExcelExportConfig("销售订单", "so", 240));

        XSSFWorkbook wb = null;
        try {
            wb = HttpExcel.newListToExcel(datas,configs);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        OutputStream outputStream = null;

        try {
            outputStream = servletResponse.getOutputStream();

            String userAgent = servletRequest.getHeader("USER-AGENT");
            String fileName = "交收报表";

            try {
                if (userAgent.contains("Mozilla")) {
                    fileName = new String(fileName.getBytes(), "ISO8859-1");
                } else {
                    fileName = URLEncoder.encode(fileName, "utf8");
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            servletResponse.setCharacterEncoding("UTF-8");
            servletResponse.setContentType("application/octet-stream; charset=UTF-8");// 设置contentType为excel格式
            servletResponse.setHeader("Content-Disposition", "Attachment;Filename=" + fileName + ".xlsx");
            wb.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}